use image::{AnimationDecoder, GenericImageView, ImageReader};

use crate::tool_result;

pub struct ImageHelper {}

impl ImageHelper {
    ///图片转字符串
    pub fn convert_image_to_ascii<T: Into<String>>(
        image_path: T,
        width: u32,
        height: u32,
    ) -> Result<String, tool_result::Error> {
        // 打开图片文件
        let img = match ImageReader::open(image_path.into()) {
            Ok(img) => img,
            Err(e) => return Err(tool_result::Error::new(e.to_string())),
        };
        let img = match img.decode() {
            Ok(img) => img,
            Err(e) => return Err(tool_result::Error::new(e.to_string())),
        };
        let resized_img = img.resize_exact(width, height, image::imageops::FilterType::Nearest);
        let ascii_img = Self::convert_to_ascii(&resized_img);
        Ok(ascii_img)
    }

    /// 将灰度图像转换为 ASCII 字符图像，返回字符串
    fn convert_to_ascii(img: &image::DynamicImage) -> String {
        let ascii_chars: &[u8] = b" %#*+=-:. ";
        let (width, height) = img.dimensions();
        let mut ascii_img = String::new();

        for y in 0..height {
            for x in 0..width {
                let pixel = img.get_pixel(x, y);
                // 取灰度值，通常是 pixel[0] 或者 0.299 * R + 0.587 * G + 0.114 * B
                let intensity =
                    (0.299 * pixel[0] as f32 + 0.587 * pixel[1] as f32 + 0.114 * pixel[2] as f32)
                        / 255.0;
                let idx = (intensity * (ascii_chars.len() - 1) as f32).round() as usize;
                let char = ascii_chars[idx] as char;
                ascii_img.push(char); // 将字符添加到字符串
            }
            ascii_img.push('\n'); // 每行结束后添加换行符
        }

        ascii_img
    }
}
